import ResUtil from "@/utils/resUtil";
import AxiosManager from "../axiosManager";
import User from "@/types/response/user";
import Notice from "../../utils/notice";

let instancce=AxiosManager.adminAxios;
async function getUseByPhone(phoneNum:string){
    let res=await instancce.get("/user/phone",{
        params:{
            phoneNum
        }
    })
    if(ResUtil.isSuccess(res)){
        return ResUtil.getData<User>(res);
    }
}
async function loginByPassword(phoneNum:string,password:string){
   let result=await instancce.get("/login/password",{
    params:{
        phoneNum,
        password
    }
   })
   if(ResUtil.isSuccess(result)){
    return ResUtil.getData<{
        token:string,
        userId:number,
        userType:number
    }>(result);
   }
   else Notice.error(ResUtil.getMessage(result));
}
async function respondentRegistry(phoneNum:string,password:string){
    let result=await instancce.post("/registry/respondent",null,{
        params:{
            phoneNum,
            password
        }
    })
    Notice.errorMsg(result);
    return ResUtil.isSuccess(result);
}
async function changeAccountByPassword(newPhone:string,oldPhone:string,
    password:number){
    let res=await instancce.put("/account",null,{
       params: {
            newPhone,
            oldPhone,
            password
        }
    })
    return ResUtil.isSuccess(res);
}
//通过id 获得用户的状态 0 为禁止 1为允许
async function getUserStateById(userId:number){
    let res=await instancce.get("/user/state",{
        params:{
            userId
        }
    })
    return ResUtil.getData<number>(res);
}
//map的key为用户账号的id  value为用户账号的状态
async function getUserStatesByIds(userIds:number[]):Promise<Map<number,number>>{
    if(userIds==null) throw new Error("userIds 不能为空");
    if(userIds.length==0) return new Map();
    console.log(userIds);
    let res=await instancce.get("/users/state",{
        params:{
            userIds
        }
    })
    let m=new Map<number,number>();
    let data=ResUtil.getData<object>(res);
    if(data!=null)
    for(let key in data){
        m.set(parseInt(key),data[key]);
    }
    return m;
}

async function changePassword(phoneNum:string,oldPwd:string,newPwd:string){
    let res=await instancce.put("/changePwd/pwd",null,{
        params:{
            phoneNum,
            oldPwd,
            newPwd
        }
    })
    return ResUtil.isSuccess(res);
}
//修改账号状态 state为0 那么不能使用 1可以使用
async function changeUserState(userId:number,state:number){
    let res=await instancce.put("/user/state",null,{
        params:{
            userId,
            state
        }
    })
    return ResUtil.isSuccess(res);
}
export{
    getUserStateById,
    getUserStatesByIds,
    getUseByPhone,
    loginByPassword,
    respondentRegistry,
    changeAccountByPassword,
    changeUserState,
    changePassword
}